package com.cjh.wc.fraud;

import org.apache.flink.annotation.Public;
import org.apache.flink.streaming.api.functions.source.FromIteratorFunction;
import org.apache.flink.walkthrough.common.entity.Transaction;

import java.io.Serializable;
import java.util.Iterator;


/**
 * @Author: CJH
 * @CreateTime: 2022-06-06  17:23
 * @Description: TODO 数据源
 * @Version: 1.0
 */
@Public
public class TransactionSource extends FromIteratorFunction<Transaction> {
    private static final long serialVersionUID = 1L;

    public TransactionSource() {
        super(new RateLimitedIterator<>(TransactionIterator.unbounded())); // 限速流来源于TransactionIterator
    }

    //内部类限速迭代器
    private static class RateLimitedIterator<T> implements Iterator<T>, Serializable {

        private static final long serialVersionUID = 1L;

        private final Iterator<T> inner;

        //构造方法私有,只能在TransactionSource类中才能被实例化
        private RateLimitedIterator(Iterator<T> inner) {
            this.inner = inner;
        }

        @Override
        public boolean hasNext() {
            return inner.hasNext();
        }

        @Override
        //重写FromIteratorFunction方法的next方法来不断生成数据流
        public T next() {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            return inner.next(); //无界流从inner data中循环生成Transaction对象
        }
    }
}
